package com.dlb.andorid.activity;

import android.app.Dialog;
import android.content.Intent;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.dlb.andorid.App;
import com.dlb.andorid.R;
import com.dlb.andorid.XContract;
import com.dlb.andorid.XServerMsg;
import com.dlb.andorid.bean.ArgPayOrder;
import com.dlb.andorid.bean.ArgPayOrderData;
import com.dlb.andorid.bean.Coupon;
import com.dlb.andorid.bean.MyAddress;
import com.dlb.andorid.bean.Order;
import com.dlb.andorid.bean.OrderCommodity;
import com.dlb.andorid.presenter.OrderPayPresenter;
import com.kwan.xframe.mvp.presenter.BasePresenter;
import com.kwan.xframe.mvp.view.activity.BaseCommonActivity;
import com.kwan.xframe.util.DialogFactory;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;


public class OrderSureActivity extends BaseCommonActivity implements XContract.IOrderPayView {

	private OrderPayPresenter mPresenter;
	private View ll_address, tv_pay, ll_coupon;
	private RecyclerView rv_product;
	private Order mOrder;
	private List<OrderCommodity> mOrderCommodities;
	private BaseQuickAdapter<OrderCommodity, BaseViewHolder> mAdapter;
	private TextView tv_coupon_num, tv_name, tv_addr, tv_time, tv_all_money, tv_send_money, tv_product_price, tv_coupon_name;
	private CheckBox cb_ali, cb_wx;
	private EditText et_remark;


	@Override
	protected void beForeSetContentView() {
		super.beForeSetContentView();
		mOrder = (Order) getIntentData("order");
		mOrderCommodities = mOrder.getCommodity_data();
	}

	@Override
	protected BasePresenter getBasePresenter() {
		mPresenter = new OrderPayPresenter(this);
		return mPresenter;
	}

	@Override
	protected void initViews() {
		super.initViews();
		tv_coupon_num = findViewById(R.id.tv_coupon_num);
		ll_coupon = findViewById(R.id.ll_coupon);
		tv_time = findViewById(R.id.tv_time);
		tv_all_money = findViewById(R.id.tv_all_money);
		tv_send_money = findViewById(R.id.tv_send_money);
		tv_product_price = findViewById(R.id.tv_product_price);
		tv_coupon_name = findViewById(R.id.tv_coupon_name);
		et_remark = findViewById(R.id.et_remark);

		tv_name = findViewById(R.id.tv_name);
		tv_addr = findViewById(R.id.tv_addr);

		cb_ali = findViewById(R.id.cb_ali);
		cb_wx = findViewById(R.id.cb_wx);

		ll_address = findViewById(R.id.ll_address);
		ll_address.setOnClickListener(this);
		tv_pay = findViewById(R.id.tv_pay);
		tv_pay.setOnClickListener(this);
		rv_product = findViewById(R.id.rv_product);

		ll_coupon.setOnClickListener(this);

		rv_product.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
		rv_product.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
		rv_product.setLayerType(View.LAYER_TYPE_HARDWARE, null);
		rv_product.setLayerType(View.LAYER_TYPE_NONE, null);

		rv_product.setHasFixedSize(true);
		rv_product.setItemAnimator(null);
		rv_product.setNestedScrollingEnabled(false);

		mAdapter = new BaseQuickAdapter<OrderCommodity, BaseViewHolder>(R.layout.list_item_order_sure_product, mOrderCommodities) {
			@Override
			protected void convert(BaseViewHolder helper, OrderCommodity item) {
				mImageLoader.loadUrl(item.getPic(), (ImageView) helper.getView(R.id.iv_icon));
				helper.setText(R.id.tv_num, item.getNum() + "");

			}
		};

		rv_product.setAdapter(mAdapter);
		cb_ali.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton compoundButton, boolean b) {

				if (b) {
					mCurrentPayType = PAY_TYPE_ALI;
					cb_wx.setChecked(false);
				}
			}
		});

		cb_wx.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton compoundButton, boolean b) {

				if (b) {
					mCurrentPayType = PAY_TYPE_WX;
					cb_ali.setChecked(false);
				}
			}
		});

//		Log.e("kwan","time1--:"+System.currentTimeMillis());
//		Log.e("kwan","time2--:"+mOrder.getAddress_time());

		Date currentTime = new Date(mOrder.getAddress_time());
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
		String dateString = formatter.format(currentTime);
		tv_time.setText(dateString);

		tv_coupon_num.setText(mOrder.getCoupon_num() + "张可用");

		tv_send_money.setText("¥ " + 0.0f);
		tv_product_price.setText("¥ " + mOrder.getTotal_sale_price());
		tv_all_money.setText("¥ " + (mOrder.getTotal_sale_price() + mAddressFee));
	}

	@Override
	protected void initData() {

	}

	@Override
	protected int getTopViewId() {
		return 0;
	}

	@Override
	protected int getMainViewId() {
		return R.layout.activity_order_sure;
	}

	@Override
	protected int getBottomViewId() {
		return 0;
	}

	@Override
	protected String getTitleTxt() {
		return "订单确认";
	}

	@Override
	public String getPageName() {
		return null;
	}


	public static final int PAY_TYPE_WX = 1;
	public static final int PAY_TYPE_ALI = 2;
	public int mCurrentPayType = PAY_TYPE_WX;
	public long mCouponId = 0;

	@Override
	public void onClick(View v) {
		super.onClick(v);
		if (v == ll_address) {

			go2ActivityForResult(AddressListActivity.class, 100, null, 0, 0);

		} else if (v == tv_pay) {

			if (mMyAddress == null) {
				toastMsg("请选择收货地址");
				return;
			}

			showProgress("");

			ArgPayOrder arg = new ArgPayOrder();
			arg.setOrder_id(mOrder.getOrder_id());
			arg.setOrder_no(mOrder.getOrder_no());
			arg.setPay_type(mCurrentPayType);
			arg.setUser_id(App.mUserInfo.getUid());

			ArgPayOrderData data = new ArgPayOrderData();
			data.setAddress_id(mMyAddress.getAddress_id());
			data.setAddress_time("" + mOrder.getAddress_time());
			data.setAddress_total_fee(mAddressFee);

			data.setCoupon_id(mCouponId);
			data.setPay_system(1);
			data.setRemarks(et_remark.getText().toString());
			arg.setData(data);
			mPresenter.payOrder(arg);

		} else if (v == ll_coupon) {

			Bundle bundle = new Bundle();
			bundle.putBoolean("isNeedResult", true);
			go2ActivityForResult(CouponListActivity.class, 300, bundle, 0, 0);

		}
	}

	float mAddressFee = 0.00f;

	@Override
	public void payOrderSuccess(XServerMsg data) {

		dismissProgress();

		if (data.getCode() == 0) {
			loadWeb(data.getMsg());
//			Bundle bundle = new Bundle();
//			bundle.putString("url", );
//			go2Activity(WebPayActivity.class, bundle, false);
		} else {
			toastMsg(data.getMsg());
		}
	}

	@Override
	public void getAddressFeeSuccess(Float data) {

		if (data != null) {

			mAddressFee = data;
			tv_send_money.setText("¥ " + mAddressFee);
			tv_product_price.setText("¥ " + mOrder.getTotal_sale_price());
			tv_all_money.setText("¥ " + (mOrder.getTotal_sale_price() + mAddressFee));
		}
	}

	protected WebView tbsWebView;

	protected void loadWeb(String loadUrl) {

		tbsWebView = findViewById(R.id.webView);
		WebSettings settings = tbsWebView.getSettings();
		settings.setJavaScriptEnabled(true);
		//https与http混合资源处理
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
			settings.setMixedContentMode(android.webkit.WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
		}
		// 设置加载进来的页面自适应手机屏幕
		settings.setUseWideViewPort(true);
		settings.setLoadWithOverviewMode(true);
		settings.setSupportZoom(true);
		settings.setBuiltInZoomControls(true);
		settings.setDisplayZoomControls(true);
		settings.setDefaultTextEncodingName("UTF-8");
		settings.setJavaScriptCanOpenWindowsAutomatically(true);

		//settings.setUserAgent( );
		final String Referer = "http://www.dilinbang.com";
		tbsWebView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
		tbsWebView.setWebViewClient(new WebViewClient() {

			@Override
			public void onLoadResource(WebView view, String url) {
				super.onLoadResource(view, url);
			}

			@Override
			public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
				super.onReceivedHttpError(view, request, errorResponse);
			}

			@Override
			public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
				handler.proceed();  // 接受所有网站的证书
				super.onReceivedSslError(view, handler, error);
			}

			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				Log.e("kwan", "shouldOverrideUrlLoading:" + url);
				if (url.startsWith("weixin://wap/pay?")) {
					Intent intent = new Intent();
					intent.setAction(Intent.ACTION_VIEW);
					intent.setData(Uri.parse(url));
					startActivityForResult(intent, 200);
					return true;
				} else {
					Map<String, String> extraHeaders = new HashMap<>();
					extraHeaders.put("Referer", Referer);
					view.loadUrl(url, extraHeaders);
					return true;
				}
			}
		});
		//需要添加到支付链接的请求头
		//String targetUrl=";  //后台返回的支付链接

		Map<String, String> extraHeaders = new HashMap<>();
		extraHeaders.put("Referer", Referer);
		tbsWebView.setWebChromeClient(new WebChromeClient() {
			@Override
			public void onProgressChanged(WebView view, int newProgress) {
				super.onProgressChanged(view, newProgress);
			}

		});

		tbsWebView.loadUrl(loadUrl, extraHeaders);

	}


	MyAddress mMyAddress;
	Coupon mCoupon;

	@Override
	protected void onResume() {
		super.onResume();
		Log.e("kwan", "onResume");
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		Log.e("kwan", "onActivityResult");

		if (requestCode == 100 && data != null) {//选择地址返回

			mMyAddress = (MyAddress) data.getBundleExtra("data").getSerializable("address");
			tv_name.setText(mMyAddress.getName() + " " + mMyAddress.getPhone());
			tv_addr.setText(mMyAddress.getProvince() + mMyAddress.getCity() + mMyAddress.getCity() + " " + mMyAddress.getAreainfo());
			mPresenter.getAddressFee(mMyAddress.getProvince_id(), mMyAddress.getCity_id());

		} else if (requestCode == 200) {

			View view = getLayoutInflater().inflate(R.layout.dialog_pay_result, null);
			final Dialog dialog = DialogFactory.showCustomDialog3(this, view);
			view.findViewById(R.id.tv_pay_ok).setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					dialog.dismiss();
					finish();
				}
			});

			view.findViewById(R.id.tv_kf).setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					dialog.dismiss();
					go2Activity(KfActivity.class, null, false);
					finish();
				}
			});

			dialog.show();
		} else if (requestCode == 300 && data != null) {

			mCoupon = (Coupon) data.getBundleExtra("data").getSerializable("coupon");
			mCouponId = mCoupon.getCoupon_id();

			tv_coupon_name.setText("-" + mCoupon.getMoney_num());
			tv_all_money.setText("¥ " + (mOrder.getTotal_sale_price() + mAddressFee - mCoupon.getMoney_num()));
		}
	}
}
